// jwt认证
import jwt, { JsonWebTokenError, JwtPayload, TokenExpiredError } from "jsonwebtoken";
import config from "../app/config";

/** 加密 */
function sign(data: any) {
    return jwt.sign(
        { admin: data }, 
        config.jwt.jwt_secret as string, 
        { expiresIn: config.jwt.jwt_expire }
    )
}

/** 解密 */
function verify(token: string): { admin: JwtPayload | string | null, error: TokenExpiredError | JsonWebTokenError | null } {
    try {
        const decoded = jwt.verify(token, config.jwt.jwt_secret as string);
        return {
            admin: decoded,
            error: null
        }
    } catch (err) {
        return {
            admin: null,
            error: err as TokenExpiredError | JsonWebTokenError | null
        }
    }
}
export {
    sign,
    verify
}